from django.contrib.auth.models import User
from rest_framework.permissions import BasePermission

from backend.decoraters import pass_safe_method


class CampusOrganizationManagingPermission(BasePermission):
    @staticmethod
    def is_manager(request, view, obj):
        for i in obj.manager_set.filter(accept=True).iterator():
            if i.owner.id == request.user.id:
                return True
        return False

    def has_update_permission(self, request, view, obj):
        return self.is_manager(request, view, obj)

    def has_destroy_permission(self, request, view, obj):
        return self.is_manager(request, view, obj)

    @pass_safe_method
    def has_object_permission(self, request, view, obj):
        # bypass.
        if request.user and (
                request.user.is_staff or request.user.is_superuser):
            return True
        if view.action == 'update' or view.action == 'partial_update':
            return self.has_update_permission(request, view, obj)
        elif view.action == 'destroy':
            return self.has_destroy_permission(request, view, obj)
        return False
